
package com.dyzx.hbb.security.handler;

import com.alibaba.fastjson.JSON;
import com.dyzx.hbb.common.base.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {

        System.out.println("\n=== Access Denied ===");
        System.out.println("Request URI: " + request.getRequestURI());
        System.out.println("Request Method: " + request.getMethod());
        System.out.println("Exception message: " + accessDeniedException.getMessage());
        System.out.println("Exception type: " + accessDeniedException.getClass().getName());

        // 获取当前认证信息
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String errorMessage;

        if (auth != null) {
            System.out.println("Current Authentication:");
            System.out.println("User: " + auth.getName());
            System.out.println("Authorities: " + auth.getAuthorities());

            // 构建详细的错误信息
            StringBuilder detailedMessage = new StringBuilder("权限不足，无法访问该资源。");
            detailedMessage.append("当前用户：").append(auth.getName());
            detailedMessage.append("，拥有权限：").append(auth.getAuthorities());

            errorMessage = detailedMessage.toString();
        } else {
            errorMessage = "权限不足，且未找到用户认证信息";
            System.out.println("No Authentication found in SecurityContext");
        }

        System.out.println("Returning error message: " + errorMessage);

        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");

        Result<Map<String, Object>> result = Result.error(403, errorMessage);
        Map<String, Object> data = new HashMap<>();
        data.put("path", request.getRequestURI());

        result.setData(data);

        response.getWriter().print(JSON.toJSONString(result));
    }
}